package com.example.minemodule.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.constants.ProjectConfigure;
import com.examination.mlib.constants.UserInfoConstants;
import com.examination.mlib.view.SuspendedBallView;
import com.example.minemodule.BR;
import com.example.minemodule.MineConstants;
import com.example.minemodule.R;
import com.example.minemodule.Utils.MineUtils;
import com.example.minemodule.databinding.MineFragmentBinding;
import com.example.minemodule.entity.MoreMenuEntity;
import com.example.minemodule.entity.OrderEntity;
import com.example.minemodule.entity.PersonCenterEntity;
import com.example.minemodule.model.MineModel;
import com.example.minemodule.ui.MineFragment;
import com.yilijk.base.AppBase;
import com.yilijk.base.base.BaseViewModel;
import com.yilijk.base.databinding.DataBindingRecyclerViewAdapter;
import com.yilijk.base.network.bean.Resource;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import crossoverone.statuslib.StatusUtil;

/**
 * Created by SHICHENG
 * on 2021/10/25.
 */
public class MineViewModel extends BaseViewModel<MineModel> {


    ArrayList<MoreMenuEntity> myOrderList = new ArrayList<>();
    ArrayList<MoreMenuEntity> inquiryDrugList = new ArrayList<>();
    ArrayList<MoreMenuEntity> healthList = new ArrayList<>();
    ArrayList<MoreMenuEntity> myCommonList = new ArrayList<>();
    ArrayList<MoreMenuEntity> myWelfareList = new ArrayList<>();
    private DataBindingRecyclerViewAdapter myOrderAdapter;
    private DataBindingRecyclerViewAdapter inquiryDrugAdapter;
    private DataBindingRecyclerViewAdapter healthAdapter;
    private DataBindingRecyclerViewAdapter myCommonAdapter;
    private DataBindingRecyclerViewAdapter myWelfareAdapter;
    private Activity activity;
    private MineFragmentBinding binding;

    public MineViewModel(@NonNull @NotNull Application application) {
        super(application);
    }

    @Override
    public void createRepository() {
        super.createRepository();
        repository = new MineModel();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
    }

    /**
     * 过去当前VM的activity binding
     */
    public void setBinding(Activity activity, MineFragmentBinding binding) {
        this.activity = activity;
        this.binding = binding;
    }

    /**
     * 设置titleBar
     */
    public void setTitleBar() {
        //设置TitileBar
        binding.setTitleBar("个人中心");
        //
        int statusH = StatusUtil.getStatusBarHeight(activity);
        if (statusH <= 0) {
            statusH = ScreenUtils.dip2px(activity, 26);
        }
        binding.mineTop.setPadding(0, statusH + ScreenUtils.dip2px(activity, 20), 0, ScreenUtils.dip2px(activity, 20));
    }

    /**
     * 设置headerView
     */
    public void setHeader() {
        binding.setName(getRepository().getName());
        binding.setAvator(getRepository().getAvator(CommonUtils.imageTranslateUri(activity, R.mipmap.default_avator)));
        binding.setVersionCode("当前版本：" + DevicesUtils.getVersionName());
    }

    /**
     * 初始化订单布局
     */
    public void initOrder() {
        binding.setOrderTitle("我的订单");
        binding.setOrderMore("全部订单");
        Integer[] orderIds = {MineConstants.OBLIGATION_ID, MineConstants.PENGING_ID, MineConstants.RECEIVING};
        String[] orderIcons = {getMipmapToUri(R.drawable.myicon1), getMipmapToUri(R.drawable.myicon2), getMipmapToUri(R.drawable.myicon3)};
        String[] orderTitles = {"待付款", "待发货", "待收货"};
        Integer[] orderCounts = {0, 0, 0};
        for (int i = 0; i < orderIds.length; i++) {
            MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
            moreMenuEntity.menu_id.set(orderIds[i]);
            moreMenuEntity.more_recycler_img.set(orderIcons[i]);
            moreMenuEntity.more_recycler_title.set(orderTitles[i]);
            moreMenuEntity.more_recycler_count.set(orderCounts[i]);
            myOrderList.add(moreMenuEntity);
        }
        binding.setMyOrderList(myOrderList);
        myOrderAdapter = new DataBindingRecyclerViewAdapter(activity, R.layout.more_recyclerview_item, BR.moreMenuBean, myOrderList);
        binding.mineOrder.orderRecyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
        binding.mineOrder.orderRecyclerView.setAdapter(myOrderAdapter);
        myOrderAdapter.setOnItemClickListener(new DataBindingRecyclerViewAdapter.ItemClickListener() {
            @Override
            public void itemClick(View view, int position) {
                Bundle bundle = new Bundle();
                switch (myOrderList.get(position).getMenu_id().get()) {
                    case MineConstants.OBLIGATION_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_order_unpaid, activity, "待付款点击");

                        bundle.putString("flag", "unpaid");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyOrder, bundle);
                        break;
                    case MineConstants.PENGING_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_order_undelivered, activity, "待发货点击");
                        bundle.putString("flag", "undelivered");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyOrder, bundle);
                        break;
                    case MineConstants.RECEIVING:
                        ClickUtils.sendEvent(ClickApi.Mine.click_order_receiving, activity, "待收货点击");
                        bundle.putString("flag", "receiving");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyOrder, bundle);
                        break;
                    default:
                        ALog.e("找不到对应orderListId");
                }
            }
        });
    }

    /**
     * 初始化福利布局
     */
    public void initWelfare() {
        binding.setWelfareTitle("我的福利");
        binding.setWelfareMore("");
        binding.mineWelfare.welfareMore.setVisibility(View.GONE);
        Integer[] welfareIds = {MineConstants.DISCOUNT_ID, MineConstants.COIN_ID,};
        String[] welfareIcons = {getMipmapToUri(R.drawable.coupon), getMipmapToUri(R.drawable.coin)};
        String[] welfareTitles = {"我的优惠券", "我的健康币"};
        Integer[] welfareCounts = {0, 0};
        for (int i = 0; i < welfareIds.length; i++) {
            MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
            moreMenuEntity.menu_id.set(welfareIds[i]);
            moreMenuEntity.more_recycler_img.set(welfareIcons[i]);
            moreMenuEntity.more_recycler_title.set(welfareTitles[i]);
            moreMenuEntity.more_recycler_count.set(welfareCounts[i]);
            myWelfareList.add(moreMenuEntity);
        }
        binding.setMyWelfareList(myWelfareList);
        myWelfareAdapter = new DataBindingRecyclerViewAdapter(activity, R.layout.more_recyclerview_item1, BR.MoreMenuBeanItem1, myWelfareList);
        binding.mineWelfare.welfareRecyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
        binding.mineWelfare.welfareRecyclerView.setAdapter(myWelfareAdapter);
        myWelfareAdapter.setOnItemClickListener(new DataBindingRecyclerViewAdapter.ItemClickListener() {
            @Override
            public void itemClick(View view, int position) {
                switch (myWelfareList.get(position).getMenu_id().get()) {
                    case MineConstants.DISCOUNT_ID:
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyCoupon);
                        ClickUtils.sendEvent(ClickApi.Mine.click_discount, activity, "我的优惠券点击");
                        break;
                    case MineConstants.COIN_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_coin, activity, "我的健康币点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyBalance);
                        break;
                    case MineConstants.ANTANG_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_antangbao, activity, "安唐保点击");
                        MineUtils.push(activity, KitArouterConstants.HOME_DOCTORBUNDLE, KitArouterConstants.Mine.AnTangBao);

                    case MineConstants.XXXR_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_xinxin, activity, "个人中心心心向荣点击");
                        getXxxrUrl();
                        break;
                }
            }
        });
    }


    /**
     * 初始化健康布局
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initInquiryDrug() {
        binding.setInquirydrugTitle("健康服务");
        binding.setInquirydrugMore("");
        binding.mineInquiryDrug.inquirtMore.setVisibility(View.GONE);
//        inquiryDrugList.add(new MoreMenuEntity(MineConstants.INQURIY_ID, getMipmapToUri(R.drawable.newindex_2), "我的问诊", 0));
        Integer[] inquiryDrugIds = {MineConstants.DOCTOR_ID, MineConstants.PRESCRIPTION_ID, MineConstants.EQUITY_ID, MineConstants.HEALTH_INQUIRY, MineConstants.HEALTH_ID, MineConstants.TEST_ID, MineConstants.SERVICE_EQUITY_ID};
        String[] inquiryDrugIcons = {getMipmapToUri(R.drawable.myicon5), getMipmapToUri(R.drawable.myicon6), getMipmapToUri(R.drawable.myicon20), getMipmapToUri(R.drawable.myicon17), getMipmapToUri(R.drawable.myicon11), getMipmapToUri(R.drawable.myicon12), getMipmapToUri(R.drawable.icon_service_equity)};
        String[] inquiryDrugTitles = {"我的医生", "我的处方", "患教报告", "就诊人", "健康数据", "健康测评", "服务权益"};
        Integer[] inquiryDrugCounts = {0, 0, 0, 0, 0, 0, 0};
        for (int i = 0; i < inquiryDrugIds.length; i++) {
            MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
            moreMenuEntity.menu_id.set(inquiryDrugIds[i]);
            moreMenuEntity.more_recycler_img.set(inquiryDrugIcons[i]);
            moreMenuEntity.more_recycler_title.set(inquiryDrugTitles[i]);
            moreMenuEntity.more_recycler_count.set(inquiryDrugCounts[i]);
            inquiryDrugList.add(moreMenuEntity);
        }
        if (!ProjectConfigure.Open.isOpenHealth) {
            inquiryDrugList.removeIf(menu_id -> menu_id.getMenu_id().get() == MineConstants.TEST_ID);
        }
        binding.setInquiryDrugList(inquiryDrugList);
        inquiryDrugAdapter = new DataBindingRecyclerViewAdapter(activity, R.layout.more_recyclerview_item1, BR.MoreMenuBeanItem1, inquiryDrugList);
        binding.mineInquiryDrug.inquirtRecyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
        binding.mineInquiryDrug.inquirtRecyclerView.setAdapter(inquiryDrugAdapter);
        inquiryDrugAdapter.setOnItemClickListener(new DataBindingRecyclerViewAdapter.ItemClickListener() {
            @Override
            public void itemClick(View view, int position) {
                switch (inquiryDrugList.get(position).getMenu_id().get()) {
                    case MineConstants.DOCTOR_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_doctor, activity, "我的医生点击");
                        ARouter.getInstance()
                                .build(ARouterConstants.Mine.MyDoctorActivity)
                                .navigation();
//                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyDoctor);
                        break;
                    case MineConstants.PRESCRIPTION_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_prescription, activity, "我的处方点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyPrescription);
                        break;
                    case MineConstants.EQUITY_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_equity, activity, "我的权益点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyJurisdiction);
                        break;
                    case MineConstants.TEST_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_test, activity, "健康测评点击");
                        ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
                                .withString("title", "健康测评")
                                .withBoolean("isShowLoading", true)
                                .withString("url", HttpUtils.getWebUrl() + "/index.html#/healthevaluation?tk=" + DevicesUtils.getToken() + "&t=" + System.currentTimeMillis())
                                .navigation();
//                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.MySeeDoctor);
                        break;
                    case MineConstants.INQURIY_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_consultation, activity, "我的问诊点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyConsultation);
                        break;
                    case MineConstants.HEALTH_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_health, activity, "健康数据点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthData);
                        break;
                    case MineConstants.HEALTH_RECORD_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_health_data, activity, "数据检测点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthRecordData);
                        break;
                    case MineConstants.HEALTH_INQUIRY:
                        ClickUtils.sendEvent(ClickApi.Mine.click_inquiry, activity, "就诊人点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MySeeDoctor);
                        break;
                    case MineConstants.SERVICE_EQUITY_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_inquiry, activity, "服务权益点击");

                        Bundle bundle = new Bundle();
                        bundle.putString("type", "1");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.ServiceEquityList, bundle);
                        break;
                    case MineConstants.My_2_DOCTOR_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_my2doctor, activity, "我的转医点击");
                        MineUtils.push(activity, KitArouterConstants.IM_DOCTORBUNDLE, KitArouterConstants.Message.MyMedicaltransfer);
                        break;
                    default:
                        ALog.e("找不到对应inquiryDrugListId");
                }

            }
        });
    }


    /**
     * 初始化健康档案布局
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initHealth() {
        binding.setHealthTitle("健康档案");
        binding.setHealthMore("");
        binding.mineHealth.healthMore.setVisibility(View.GONE);
//        inquiryDrugList.add(new MoreMenuEntity(MineConstants.INQURIY_ID, getMipmapToUri(R.drawable.newindex_2), "我的问诊", 0));
        Integer[] healthIds = {MineConstants.HEALTH_DATA, MineConstants.HEALTH_RECORD, MineConstants.HEALTH_REPORT, MineConstants.HEALTH_HISTORY, MineConstants.HEALTH_HOBBY};
        String[] healthIcons = {getMipmapToUri(R.drawable.myicon13), getMipmapToUri(R.drawable.icon_record), getMipmapToUri(R.drawable.myicon14), getMipmapToUri(R.drawable.myicon15), getMipmapToUri(R.drawable.myicon16)};
        String[] healthTitles = {"健康检测", "我的报告", "评测报告", "健康史", "生活方式"};
        Integer[] inquiryDrugCounts = {0, 0, 0, 0, 0};
        for (int i = 0; i < healthIds.length; i++) {
            MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
            moreMenuEntity.menu_id.set(healthIds[i]);
            moreMenuEntity.more_recycler_img.set(healthIcons[i]);
            moreMenuEntity.more_recycler_title.set(healthTitles[i]);
            moreMenuEntity.more_recycler_count.set(inquiryDrugCounts[i]);
            healthList.add(moreMenuEntity);
        }

        if (!ProjectConfigure.Open.isOpenHealth) {
            healthList.removeIf(menu_id -> menu_id.getMenu_id().get() == MineConstants.HEALTH_REPORT);
        }
        binding.setHealthList(healthList);
        healthAdapter = new DataBindingRecyclerViewAdapter(activity, R.layout.more_recyclerview_item1, BR.MoreMenuBeanItem1, healthList);
        binding.mineHealth.healthRecyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
        binding.mineHealth.healthRecyclerView.setAdapter(healthAdapter);
        healthAdapter.setOnItemClickListener(new DataBindingRecyclerViewAdapter.ItemClickListener() {
            @Override
            public void itemClick(View view, int position) {
                Bundle bundle = new Bundle();
                switch (healthList.get(position).getMenu_id().get()) {
                    case MineConstants.HEALTH_DATA:
                        ClickUtils.sendEvent(ClickApi.Mine.click_health_data, activity, "数据检测点击");
                        bundle.putInt("type", 0);
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthRecordData, bundle);
                        break;
                    case MineConstants.HEALTH_REPORT:
                        ClickUtils.sendEvent(ClickApi.Mine.click_health_report, activity, "评测报告点击");
                        bundle.putInt("type", 3);
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthRecordData, bundle);
                        break;
                    case MineConstants.HEALTH_HISTORY:
                        ClickUtils.sendEvent(ClickApi.Mine.click_health_history, activity, "健康史点击");
                        bundle.putInt("type", 1);
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthRecordData, bundle);
                        break;
                    case MineConstants.HEALTH_HOBBY:
                        ClickUtils.sendEvent(ClickApi.Mine.click_health_hobby, activity, "生活习惯点击");
                        bundle.putInt("type", 2);
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthRecordData, bundle);
                        break;
                    case MineConstants.HEALTH_RECORD:
//                        ClickUtils.sendEvent(ClickApi.Mine.click_health_hobby,activity,"生活习惯点击");
                        bundle.putInt("type", 4);
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthRecordData, bundle);

                        break;
                    default:
                        ALog.e("找不到对应healthListId");
                }

            }
        });
    }

    /**
     * 初始化common
     */

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initCommon() {
        binding.setCommonTitle("常用");
        binding.setCommonMore("");
        binding.mineCommon.commonMore.setVisibility(View.GONE);
        Integer[] commonIds = {MineConstants.ADDRESS_ID, MineConstants.HELP_ID, MineConstants.PERSONALIZED_ID, MineConstants.SETTING_ID};
        String[] commonIcons = {getMipmapToUri(R.drawable.myicon9), getMipmapToUri(R.mipmap.img_customer_center), getMipmapToUri(R.drawable.icon_self), getMipmapToUri(R.drawable.icon_setting)};
        String[] commonTitles = {"收货地址", "帮助中心", "个性化推荐", "设置"};
        Integer[] commonCounts = {0, 0, 0, 0};
        for (int i = 0; i < commonIds.length; i++) {
            MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
            moreMenuEntity.menu_id.set(commonIds[i]);
            moreMenuEntity.more_recycler_img.set(commonIcons[i]);
            moreMenuEntity.more_recycler_title.set(commonTitles[i]);
            moreMenuEntity.more_recycler_count.set(commonCounts[i]);
            myCommonList.add(moreMenuEntity);
        }


//        MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
//        moreMenuEntity.menu_id.set(MineConstants.XINXIN_ID);
//        moreMenuEntity.more_recycler_img.set(getMipmapToUri(R.drawable.myicon9));
//        moreMenuEntity.more_recycler_title.set("心心向榮");
//        moreMenuEntity.more_recycler_count.set(1);
//        myCommonList.add(moreMenuEntity);

        if (!ProjectConfigure.Open.isOpenSetting) {
            myCommonList.removeIf(menu_id -> menu_id.getMenu_id().get() == MineConstants.SETTING_ID);
        }
        binding.setMyCommonList(myCommonList);
        myCommonAdapter = new DataBindingRecyclerViewAdapter(activity, R.layout.more_recyclerview_item1, BR.MoreMenuBeanItem1, myCommonList);
        binding.mineCommon.commonRecyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
        binding.mineCommon.commonRecyclerView.setAdapter(myCommonAdapter);
        myCommonAdapter.setOnItemClickListener(new DataBindingRecyclerViewAdapter.ItemClickListener() {
            @Override
            public void itemClick(View view, int position) {
                switch (myCommonList.get(position).getMenu_id().get()) {
                    case MineConstants.ADDRESS_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_address, activity, "收货地址点击");
                        Bundle bundle = new Bundle();
                        bundle.putString("tag", "manager");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyAddress, bundle);
                        break;
                    case MineConstants.HELP_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_help, activity, "帮助与反馈点击");
//                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HelpAndBackPage);
//                        String url = "https://activity.d1.yilijk.com";
//                        String url = "http://192.168.7.89:8080/#/customer-service?";
                        String url = HttpUtils.getWebUrl() + "#/customer-service?tk=" + DevicesUtils.getToken() + "&t=" + System.currentTimeMillis();
                        ARouter.getInstance()
                                .build(ARouterConstants.MineWebviewActivity)
                                .withString("title", "帮助中心")
                                .withString("url", url)
//                                .withString("url", "https://activity.d1.yilijk.com/#/customer-service?tk=eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyMDkxNjgxMTE4OTQ1MjkiLCJ0eXBlIjoyLCJzb3VyY2UiOjkwMDIsImxvZ2luVHlwZSI6IjEiLCJ0aW1lIjoxNjU1ODE3NjExMDA1fQ.-M0c2bgO4s9oE7NcKoEDorb5OwmOxqvYdX3ORSJne5Q&t=1655862507")
//                                .withString("url", "http://192.168.7.89:8080/#/customer-service?tk=eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjkyMTY2MTQwMzk1NTMiLCJ0eXBlIjoyLCJzb3VyY2UiOjkwMDAsInRpbWUiOjE2NTQ2NTI0ODkwNDB9.hMhu2gsz2CPzNF5LMVHKaIgKW3-J8dnp0l4HHZ0stG4&t=121231123123123123")
//                                .withString("url", "http://192.168.7.89:8080/#/customer-service")
                                .withBoolean("ishtml", false)
                                .navigation();
                        break;
                    case MineConstants.XINXIN_ID:
                        MineUtils.push(activity, KitArouterConstants.HOME_DOCTORBUNDLE, KitArouterConstants.Mine.Xinxin);
                        break;
                    case MineConstants.PERSONALIZED_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_personalized, activity, "个性化推荐点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.PersonalizedSetting);

//                        String account_id = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_id, "");
//                        if (TextUtils.isEmpty(account_id)) {
//                            return;
//                        }
//
//                        if (ActivityManagerUtils.getLastestActivity() != null) {
//                            LoadingUtils.getLoadingUtils(ActivityManagerUtils.getLastestActivity()).showLoading();
//                        }
//                        getRepository().getUserAction(new HttpCallBack<UserActionEntity>() {
//                            @Override
//                            public void onSuccess(UserActionEntity userActionEntity, int i) {
//                                if (ActivityManagerUtils.getLastestActivity() != null) {
//                                    LoadingUtils.getLoadingUtils(ActivityManagerUtils.getLastestActivity()).dismissLoading();
//                                }
//                                Bundle bundle = new Bundle();
//                                bundle.putString("accountId", account_id + "");
//                                bundle.putBoolean("openStatus", "1".equals(userActionEntity.getData()));
//                                MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.PersonalizedSetting, bundle);
//                            }
//
//                            @Override
//                            public void onFailure(String s, int i) {
//                                if (ActivityManagerUtils.getLastestActivity() != null) {
//                                    LoadingUtils.getLoadingUtils(ActivityManagerUtils.getLastestActivity()).dismissLoading();
//                                }
//                                Bundle bundle = new Bundle();
//                                bundle.putString("accountId", account_id + "");
//                                bundle.putBoolean("openStatus", false);
//                                MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.PersonalizedSetting, bundle);
//                            }
//                        });
                        break;
                    case MineConstants.SETTING_ID:
                        ClickUtils.sendEvent(ClickApi.Mine.click_Setting, activity, "设置点击");
                        MineUtils.push(activity, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.Setting);
                        break;

                }
            }
        });
    }

    /**
     * 处理图片转换Uri
     */
    public String getMipmapToUri(int resId) {
        String uriStr = "";
        try {
            Resources r = AppBase.getApplication().getResources();
            Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                    + r.getResourcePackageName(resId) + "/"
                    + r.getResourceTypeName(resId) + "/"
                    + r.getResourceEntryName(resId));
            uriStr = uri.toString();
        } catch (Throwable throwable) {
            ALog.e(throwable.getMessage().toString().trim());
        }
        return uriStr;
    }

    /**
     * 获取PersonCenter
     */
    public LiveData<Resource<PersonCenterEntity.DataBean>> getPersonCenter() {
        return getRepository().getPersonCenter();
    }

    /**
     * 获取Order
     */
    public LiveData<Resource<OrderEntity.DataBean>> getOrder() {
        return getRepository().getOrder();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void requestData(MineFragment mineFragment) {
        getRepository().getPersonCenterNew(new HttpCallBack<PersonCenterEntity>() {
            @Override
            public void onSuccess(PersonCenterEntity personCenterEntity, int i) {
                if (personCenterEntity.isResult()) {
                    PersonCenterEntity.DataBean data = personCenterEntity.getData();
                    if (data.getAccount() != null) {
                        if (!TextUtils.isEmpty(data.getAccount().getAvatar())) {
                            SharedPreferencesUtils.getInstance().save(UserInfoConstants.account_imgUrl, data.getAccount().getAvatar());
                        }
                        if (!TextUtils.isEmpty(data.getAccount().getMobile())) {
                            SharedPreferencesUtils.getInstance().save(UserInfoConstants.account_mobile, data.getAccount().getMobile());
                        }
                        if (!TextUtils.isEmpty(data.getAccount().getNickname())) {
                            SharedPreferencesUtils.getInstance().save(UserInfoConstants.account_nickName, data.getAccount().getNickname());
                        }
                    }

                    myWelfareList.removeIf(item -> item.menu_id.get() == MineConstants.XXXR_ID);
                    if (data.isHeartToward()) {
                        MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
                        moreMenuEntity.menu_id.set(MineConstants.XXXR_ID);
                        moreMenuEntity.more_recycler_img.set(getMipmapToUri(R.mipmap.icon_xxxr));
                        moreMenuEntity.more_recycler_title.set("心心向荣");
                        moreMenuEntity.more_recycler_count.set(0);
                        myWelfareList.add(moreMenuEntity);
                        myWelfareAdapter.notifyDataSetChanged();
                    }


                    myWelfareList.removeIf(item -> item.menu_id.get() == MineConstants.ANTANG_ID);
                    if (data.isAtbEnable()) {
                        MoreMenuEntity my2doctor = new MoreMenuEntity();
                        my2doctor.menu_id.set(MineConstants.ANTANG_ID);
                        my2doctor.more_recycler_img.set(getMipmapToUri(R.drawable.icon_antangbao));
                        my2doctor.more_recycler_title.set("安唐保");
                        my2doctor.more_recycler_count.set(0);
                        myWelfareList.add(my2doctor);
                    }
                    binding.setMyWelfareList(myWelfareList);
                    myWelfareAdapter.notifyDataSetChanged();

                    if (data.isHealthRecordsEnable()) {
                        binding.setShowMineHealth(true);
                        if (ProjectConfigure.Open.isOpenHealth) {
                            int index = 0;
                            inquiryDrugList.removeIf(menu_id -> menu_id.getMenu_id().get() == MineConstants.TEST_ID);
                            for (MoreMenuEntity m : inquiryDrugList
                            ) {
                                if (m.getMenu_id().get() == MineConstants.HEALTH_ID) {
                                    index = inquiryDrugList.indexOf(m);
                                }
                            }
                            MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
                            moreMenuEntity.menu_id.set(MineConstants.TEST_ID);
                            moreMenuEntity.more_recycler_img.set(getMipmapToUri(R.drawable.myicon12));
                            moreMenuEntity.more_recycler_title.set("健康测评");
                            moreMenuEntity.more_recycler_count.set(0);
                            inquiryDrugList.add(index + 1, moreMenuEntity);
                        }

                        binding.setHealthList(healthList);
                        healthAdapter.notifyDataSetChanged();


                    } else {
                        inquiryDrugList.removeIf(menu_id -> menu_id.getMenu_id().get() == MineConstants.TEST_ID);
                        binding.setInquiryDrugList(inquiryDrugList);
                        binding.setShowMineHealth(false);
                    }

                    inquiryDrugList.removeIf(menu_id -> menu_id.getMenu_id().get() == MineConstants.My_2_DOCTOR_ID);
                    MoreMenuEntity my2doctor = new MoreMenuEntity();
                    my2doctor.menu_id.set(MineConstants.My_2_DOCTOR_ID);
                    my2doctor.more_recycler_img.set(getMipmapToUri(R.mipmap.icon_my2doctor));
                    my2doctor.more_recycler_title.set("我的转医");
                    my2doctor.more_recycler_count.set(0);
                    inquiryDrugList.add(my2doctor);
                    binding.setHealthList(healthList);
                    healthAdapter.notifyDataSetChanged();

                    inquiryDrugAdapter.notifyDataSetChanged();
                    if (data.getPreference().getValue().equals("1")) {
                        if (binding.getInquiryDrugList().get(0).getMenu_id().get() != MineConstants.INQURIY_ID) {
                            MoreMenuEntity moreMenuEntity = new MoreMenuEntity();
                            moreMenuEntity.menu_id.set(MineConstants.INQURIY_ID);
                            moreMenuEntity.more_recycler_img.set(getMipmapToUri(R.drawable.newindex_2));
                            moreMenuEntity.more_recycler_title.set("我的问诊");
                            moreMenuEntity.more_recycler_count.set(0);
                            inquiryDrugList.add(0, moreMenuEntity);
                            inquiryDrugAdapter.notifyDataSetChanged();
                        }
                    }
                    if (data.getAccount() != null) {
                        if (!TextUtils.isEmpty(data.getAccount().getNickname())) {
                            binding.setName(data.getAccount().getNickname());
                            SharedPreferencesUtils.getInstance().save(UserInfoConstants.account_nickName, data.getAccount().getNickname());
                        }
                        if (!TextUtils.isEmpty(data.getAccount().getMobile())) {
                            SharedPreferencesUtils.getInstance().save(UserInfoConstants.account_mobile, data.getAccount().getMobile());
                            if (binding.getName().isEmpty()) {
                                binding.setName(data.getAccount().getMobile());
                            }
                        }
                        if (!TextUtils.isEmpty(data.getAccount().getUserNo())) {
                            SharedPreferencesUtils.getInstance().save(UserInfoConstants.account_userNo, data.getAccount().getUserNo());
                        }
                        if (!TextUtils.isEmpty(data.getAccount().getAvatar())) {
                            binding.setAvator(data.getAccount().getAvatar());
                            SharedPreferencesUtils.getInstance().save(UserInfoConstants.account_imgUrl, data.getAccount().getAvatar());
                        }
                    }
                    if (data.getEmployee() != null) {
                        if (!TextUtils.isEmpty(data.getEmployee().getEmail())) {
                            binding.setEmployeeAccountIv(true);
                            if (data.getEmployee().getEmail().indexOf("@") > 0) {
                                binding.veiwWaterMaster.refreshEmail(data.getEmployee().getEmail().split("@")[0]);
                            }
                        } else {
                            binding.setEmployeeAccountIv(false);
                        }
                    }
//                    if (TextUtils.isEmpty(data.getReleaseStatus())){
//                        if (data.getEmployee()!=null){
//                            if (!TextUtils.isEmpty(data.getEmployee().getEmail())){
//                                binding.setEmployeeAccountIv(true);
//                                if (data.getEmployee().getEmail().indexOf("@") > 0) {
//                                    binding.veiwWaterMaster.refreshEmail(data.getEmployee().getEmail().split("@")[0]);
//                                }
//                            }else{
//                                binding.setEmployeeAccountIv(false);
//                            }
//                        }
//                    }else{
//                        if (data.getReleaseStatus().equals("1")){
//                            binding.setEmployeeAccountIv(true);
//                            if (data.getEmployee().getEmail().indexOf("@") > 0) {
//                                binding.veiwWaterMaster.refreshEmail(data.getEmployee().getEmail().split("@")[0]);
//                            }
//                        }else{
//                            binding.setEmployeeAccountIv(false);
//                        }
//                    }

                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
        getOrder().observe(mineFragment, new Observer<Resource<OrderEntity.DataBean>>() {
            @Override
            public void onChanged(Resource<OrderEntity.DataBean> dataBeanResource) {
                if (dataBeanResource.data != null) {
                    for (int i = 0; i < myOrderList.size(); i++) {
                        if (myOrderList.get(i).getMenu_id().get() == MineConstants.OBLIGATION_ID) {
                            myOrderList.get(i).more_recycler_count.set(dataBeanResource.data.getUnpaidCount());
                        }
                        if (myOrderList.get(i).getMenu_id().get() == MineConstants.PENGING_ID) {
                            myOrderList.get(i).more_recycler_count.set(dataBeanResource.data.getUndeliveredCount());
                        }
                        if (myOrderList.get(i).getMenu_id().get() == MineConstants.RECEIVING) {
                            myOrderList.get(i).more_recycler_count.set(dataBeanResource.data.getReceivingCount());
                        }
                    }
                    myOrderAdapter.notifyDataSetChanged();
                }
            }
        });
        suspendedBallView();
    }

    /**
     * 悬浮球是否显示
     * SuspendedBallView.HiddenCallBack()
     */
    public void suspendedBallView() {
        binding.suspendedBallView.isHiddenSuspendedBallView(3, new SuspendedBallView.HiddenCallBack() {
            @Override
            public void hidden(boolean hidden) {
                if (hidden) {
                    binding.suspendedBallView.setVisibility(View.GONE);
                } else {
                    binding.suspendedBallView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void setIcon(String iconUrl) {
                if (iconUrl != null) {
                    binding.suspendedBallView.setGifIcon(iconUrl);
                } else {
                    binding.suspendedBallView.setGifIcon(R.drawable.icon_default_square);
                }
            }

            @Override
            public void getUrl(String url) {
                binding.suspendedBallView.setActivityUrl(url);
            }

        });
    }

    void getXxxrUrl() {
        getRepository().getJumpUrl(SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_passportId, ""), new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("data") && !TextUtils.isEmpty(jsonObject.getString("data"))) {
                        ARouter.getInstance()
                                .build(ARouterConstants.MineWebviewActivity)
                                .withString("title", "心心向荣")
                                .withString("url", jsonObject.getString("data"))
                                .withBoolean("ishtml", false)
                                .navigation();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }

}
